package com.yk.faceapplication.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.allinpay.xed.R;
import com.android.volley.VolleyError;
import com.yk.faceapplication.callback.RequestCallback;
import com.yk.faceapplication.entity.ProductDetail;
import com.yk.faceapplication.entity.ShowProductPoint;
import com.yk.faceapplication.entity.StudyInfo;
import com.yk.faceapplication.http.RequestUrl;
import com.yk.faceapplication.util.ActivityUtil;
import com.yk.faceapplication.util.ImageUtil;
import com.yk.faceapplication.util.LogDebugger;
import com.yk.faceapplication.util.RequestUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class ProductDetailActivity extends BaseActivity {
    private ProductDetail productDetail;
    private TextView loanAmountTV, loanTimeTV, loanMinRateTV, loanTypeTV, loanType2TV;
    private ImageView productIconIV;
    private TextView productNameTV, productLableTV, productConditionTV, productDescriptionTV;
    private TextView commitTV;
    private TextView termTV, payTypeTV, payTimeTV;

    private EditText loanAmtET, loanTermET;
    private String[] progressList;

    private Button authCardBtn, authMobileBtn, authBankBtn;
    private TextView authCardLine, authMobileLine, authBankLine;

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch ((v.getId())) {
            case R.id.commit_tv:
                if (ActivityUtil.editIsNull(loanAmtET)) {
                    Toast.makeText(mApplication, "请输入金额", Toast.LENGTH_LONG).show();
                    return;
                }
                if (ActivityUtil.editIsNull(loanTermET)) {
                    Toast.makeText(mApplication, "请输入期限", Toast.LENGTH_LONG).show();
                    return;
                }
                double amount = Double.valueOf(loanAmtET.getText().toString().trim());
                double amountMin = Double.valueOf(productDetail.getMinLoanAmt());
                double amountMax = Double.valueOf(productDetail.getMaxLoanAmt());
                if (amount < amountMin || amount > amountMax) {
                    Toast.makeText(mApplication, "输入金额不符合要求", Toast.LENGTH_LONG).show();
                    return;
                }
                double term = Double.valueOf(loanTermET.getText().toString().trim());
                double termMin = Double.valueOf(productDetail.getMinLoanTerm());
                double termMax = Double.valueOf(productDetail.getMaxLoanTerm());
                if (term < termMin || term > termMax) {
                    Toast.makeText(mApplication, "输入期限不符合要求", Toast.LENGTH_LONG).show();
                    return;
                }
                requestLoan();
                break;
        }
    }


    private void getProductLoanTypeAndTerm() {

        Map<String, String> form = new HashMap<String, String>();

        RequestCallback callback = new RequestCallback() {
            @Override
            public void success(JSONObject jsonObject) {
                try {
                    StudyInfo loanTermInfo = JSON.parseObject(jsonObject.getJSONObject("data").getString("xed-product-audit-online"), StudyInfo.class);
                    termTV.setText("审核周期：" + loanTermInfo.getValue());
                    StudyInfo loanTypeInfo = JSON.parseObject(jsonObject.getJSONObject("data").getString("xed-product-repayment-method"), StudyInfo.class);
                    payTypeTV.setText("还款方式：" + loanTypeInfo.getValue());

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(VolleyError volleyError) {

            }
        };
        RequestUtil.request(this, RequestUrl.GET_PRUDUCT_LOAD_TYPE_TERM, callback, form);
    }

    private void requestLoanPoint() {

        Map<String, String> form = new HashMap<String, String>();
        form.put("productShowId", productDetail.getLoanShowId());
        form.put("categoryId", productDetail.getBaseProduct().getCategoryId());
        form.put("orgId", productDetail.getBaseProduct().getOrgId());
        form.put("loanTerm", loanTermET.getText().toString().trim());
        form.put("applyAmount", loanAmtET.getText().toString().trim());
        form.put("loanTermType", productDetail.getLoanTermType());
        form.put("userAgentCode", "2");

        RequestCallback callback = new RequestCallback() {
            @Override
            public void success(JSONObject jsonObject) {

            }

            @Override
            public void fail(VolleyError volleyError) {

            }
        };
        RequestUtil.request(this, RequestUrl.REQUEST_LOAN_POINT + "token=" + mToken, callback, form);
    }

    private void requestLoan() {

        commitTV.setEnabled(false);
        Map<String, String> form = new HashMap<String, String>();
        form.put("memberId", mApplication.getMember().getId());
        form.put("mobile", mApplication.getMember().getMobile());
        form.put("realName", mApplication.getMember().getRealName());
        form.put("identityId", mApplication.getMember().getPeople().getIdCardNo());
        form.put("loanShowId", productDetail.getLoanShowId());
        form.put("orgId", productDetail.getBaseProduct().getOrgId());
        form.put("loanAmt", loanAmtET.getText().toString().trim());
        form.put("loanTerm", loanTermET.getText().toString().trim());
        form.put("termType", productDetail.getLoanTermType());


        RequestCallback callback = new RequestCallback() {
            @Override
            public void success(JSONObject jsonObject) {
                commitTV.setEnabled(true);
                Toast.makeText(mApplication, "申请成功", Toast.LENGTH_LONG).show();
                requestLoanPoint();
                //                Intent intent = new Intent(ProductDetailActivity.this,AddBillActivity.class);
                //                intent.putExtra("icon",productDetail.getProductIconId());
                //                intent.putExtra("id",productDetail.getLoanShowId());
                //                intent.putExtra("name",productDetail.getBaseProduct().getProductName());
                //                intent.putExtra("orgId",productDetail.getBaseProduct().getOrgId());
                //                startActivity(intent);
                //                mApplication.setHomePageGetMember(true);
                String url = productDetail.getLoanApplyUrl();
                if(url != null){
                    url = url.replace("${token}",mToken).replace("${memberId}",mApplication.getMember().getId()).replace("${productId}",productDetail.getBaseProduct().getProductId());

                    Intent intent = new Intent(ProductDetailActivity.this, WebviewActivity.class);
                    intent.putExtra("url", url);
                    startActivity(intent);
                    finishAct();
                }
            }

            @Override
            public void fail(VolleyError volleyError) {
                commitTV.setEnabled(true);
            }
        };
        RequestUtil.request(this, RequestUrl.REQUEST_LOAN + "token=" + mToken, callback, form);
    }

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);

        authCardLine = (TextView) findViewById(R.id.auth_card_line);
        authMobileLine = (TextView) findViewById(R.id.auth_mobile_line);
        authBankLine = (TextView) findViewById(R.id.auth_bank_line);
        authCardBtn = (Button) findViewById(R.id.auth_card_btn);
        authMobileBtn = (Button) findViewById(R.id.auth_mobile_btn);
        authBankBtn = (Button) findViewById(R.id.auth_bank_btn);

        loanAmountTV = (TextView) findViewById(R.id.loan_amount_tv);
        loanTimeTV = (TextView) findViewById(R.id.loan_time_tv);
        loanMinRateTV = (TextView) findViewById(R.id.loan_min_rate_tv);
        productIconIV = (ImageView) findViewById(R.id.product_icon);
        productNameTV = (TextView) findViewById(R.id.product_name_tv);
        productLableTV = (TextView) findViewById(R.id.loan_lable_tv);
        productConditionTV = (TextView) findViewById(R.id.loan_condition_tv);
        productDescriptionTV = (TextView) findViewById(R.id.loan_description_tv);
        commitTV = (TextView) findViewById(R.id.commit_tv);
        commitTV.setOnClickListener(this);

        termTV = (TextView) findViewById(R.id.loan_term_tv);
        payTypeTV = (TextView) findViewById(R.id.loan_pay_type_tv);
        payTimeTV = (TextView) findViewById(R.id.loan_pay_time_tv);
        loanType2TV = (TextView) findViewById(R.id.loan_type2_tv);
        loanTypeTV = (TextView) findViewById(R.id.loan_type_tv);

        loanAmtET = (EditText) findViewById(R.id.loan_amount_et);


        //在一开始声明TextWatcher，在afterTextChange内操作
        TextWatcher mTextWatcher=new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                String text = s.toString();
                int len = s.toString().length();
                if (len == 1 && text.equals("0")) {
                    s.clear();
                }
            }
        };

        loanAmtET.addTextChangedListener(mTextWatcher);
        loanTermET = (EditText) findViewById(R.id.loan_term_et);
        loanTermET.addTextChangedListener(mTextWatcher);
        getProductDetail(getIntent().getStringExtra("loanShowId"));
        getProductLoanTypeAndTerm();
    }

    private void showProductsPoint(ProductDetail productDetail) {
        List<ShowProductPoint> points = new ArrayList<>();
        ShowProductPoint showProductPoint = new ShowProductPoint();
        showProductPoint.setCategoryId(productDetail.getBaseProduct().getCategoryId());
        showProductPoint.setLoanTerm(productDetail.getMaxLoanTerm());
        showProductPoint.setLoanTermType(productDetail.getLoanTermType());
        showProductPoint.setOrgId(productDetail.getBaseProduct().getOrgId());
        showProductPoint.setProductShowId(productDetail.getLoanShowId());
        showProductPoint.setUserAgentCode("2");
        points.add(showProductPoint);
//        Object jsonObject = com.alibaba.fastjson.JSONArray.toJSON(points);
//        com.alibaba.fastjson.JSONObject jso=JSON.parseObject(com.alibaba.fastjson.JSONObject.toJSONString(points));//json字符串转换成jsonobject对象
//        LogDebugger.info(jso+"");
        LogDebugger.info(com.alibaba.fastjson.JSONObject.toJSONString(points));
        RequestUtil.request(RequestUrl.DOMAN+"allinpay.stat.all/statall/productlist/add?showType=2&token=" + mToken + "&appType=app",com.alibaba.fastjson.JSONObject.toJSONString(points));

//        RequestCallback callback = new RequestCallback() {
//            @Override
//            public void success(JSONObject jsonObject) {
//
//            }
//
//            @Override
//            public void fail(VolleyError volleyError) {
//
//            }
//        };
//        RequestUtil.request(this, "http://openapi.allinpaycard.cn/allinpay.stat.all/statall/productlist/add?showType=2&token=" + mToken + "&appType=app", callback, jsonObject);
    }


    private void getProductDetail(String loanShowId) {

        final Map<String, String> form = new HashMap<String, String>();
        form.put("loanShowId", loanShowId);

        RequestCallback callback = new RequestCallback() {
            @Override
            public void success(JSONObject jsonObject) {
                try {
                    productDetail = JSON.parseObject(jsonObject.getString("data"), ProductDetail.class);
                    showProductsPoint(productDetail);
                    //                    loanAmtET.setFilters(new InputFilter[] { new InputFilterMinMax("0", productDetail.getMaxLoanAmt()) });
                    //
                    //                    loanTermET.setFilters(new InputFilter[] { new InputFilterMinMax("0", productDetail.getMaxLoanTerm()) });

                    progressList = productDetail.getApplyProcess().split("|");

                    for (String progress : progressList) {
                        if (progress.equalsIgnoreCase("A")) {
                            authCardLine.setVisibility(View.VISIBLE);
                            authCardBtn.setVisibility(View.VISIBLE);
                        } else if (progress.equalsIgnoreCase("B")) {
                            authMobileLine.setVisibility(View.VISIBLE);
                            authMobileBtn.setVisibility(View.VISIBLE);
                        } else if (progress.equalsIgnoreCase("C")) {
                            authBankLine.setVisibility(View.VISIBLE);
                            authBankBtn.setVisibility(View.VISIBLE);
                        }
                    }

                    loanAmountTV.setText(productDetail.getMinLoanAmt() + "-" + productDetail.getMaxLoanAmt());
                    loanTimeTV.setText(productDetail.getMinLoanTerm() + "-" + productDetail.getMaxLoanTerm());
                    loanMinRateTV.setText("低至" + Double.valueOf(productDetail.getMinLoanRate()) + "%");
                    ImageUtil.displayImage(mApplication, productDetail.getProductIconId(), productIconIV);
                    productNameTV.setText(productDetail.getBaseProduct().getProductName());
                    productLableTV.setText(productDetail.getLoanLabel());
                    productConditionTV.setText(productDetail.getApplyCondition());
                    productDescriptionTV.setText(productDetail.getBaseProduct().getDescription());

                    //                    termTV.setText("审核周期：" + productDetail.getAuditCycle());
                    payTimeTV.setText("放款时间：最快" + productDetail.getFastestEndingTime() + "分钟放款");
                    //                    payTypeTV.setText("还款方式：" + productDetail.getRepaymentMethod());
                    String loanType;
                    switch (productDetail.getLoanTermType()) {
                        case "D":
                            loanType = "（天）";
                            break;
                        case "M":
                            loanType = ("（月）");
                            break;
                        default:
                            loanType = ("（年）");
                            break;
                    }
                    loanTypeTV.setText("期限" + loanType);
                    loanType2TV.setText("借款期限" + loanType);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(VolleyError volleyError) {

            }
        };
        RequestUtil.request(this, RequestUrl.GET_PRODUCT_DETAIL + "token=" + mToken, callback, form);
    }
}
